package com.shujia.flink.tf;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.SlidingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;

public class Demo06Window {
    public static void main(String[] args) throws Exception {
        // Flink窗口操作：时间、计数、会话

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStream<String> ds = env.socketTextStream("master", 8888);
        SingleOutputStreamOperator<Tuple2<String, Integer>> kvDS = ds.map(word -> Tuple2.of(word, 1), Types.TUPLE(Types.STRING, Types.INT));

        // 每隔5s钟统计每个单词的数量 ---> 滚动窗口实现
        SingleOutputStreamOperator<Tuple2<String, Integer>> outputDS01 = kvDS
                .keyBy(kv -> kv.f0, Types.STRING)
                .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
                .sum(1);

//        outputDS01.print();
        // 每隔5s钟统计最近10s内的每个单词的数量 ---> 滑动窗口实现
        kvDS
                .keyBy(kv -> kv.f0, Types.STRING)
                .window(SlidingProcessingTimeWindows.of(Time.seconds(10), Time.seconds(5)))
                .sum(1)
                .print();

        env.execute();
    }
}
